package com.telsoft.kqxs;

import java.util.ArrayList;


import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ProvinceProperties extends ListActivity {
	private static final String TAG1 = "time1";
	private static final String TAG2 = "time2";
	private static final String TAG3 = "time3";
	String[] Provinces = { 	"Mien Bac", "Binh Dinh",  "Da Nang" , "Dac Lac",  "Dac Nong",  "Gia Lai","Khanh Hoa","Kom Tum", "Ninh Thuan", "Phu Yen",
			"Quang Binh", "Quang Nam", "Quang Ngai", "Quang Tri", "Thua Thien Hue", "An Giang", "Bac Lieu", "Ben Tre", "Binh Duong", "Binh Phuoc",
			"Binh Thuan","Ca Mau", "Can Tho","Dong Nai", "Dong Thap", "Hau Giang", "Kien Giang", "Lam Dong", "Long An", "Soc Trang", "TP Ho Chi Minh",
			"Tay Ninh", "Tien Giang", "Tra Vinh", "Vinh Long", "Vung Tau"			
 	};
	private static final String URL = "http://210.211.98.84/webicm/ts/ProvinceLottery.xml";
	private static final String ID = "ProvinceID";
	private static final String CODE = "ProvinceCode";
	private static final String NAME = "ProvinceName";
	private static final String id = "id";
	
	String xml;
	DBAdapter db;
	HashMap<String, String> map;
	NodeList nodes;
	ArrayList<HashMap<String, String>> mylist;
	Province province;
	Document doc;
	
	private static final String DEBUG_TAG = "NetworkStatusExample";
		
	 public void onCreate(Bundle savedInstanceState){
		 
		 super.onCreate(savedInstanceState);
		 setContentView(R.layout.province_list);
		 db = new DBAdapter(this);
		
		 
		 province = new Province();
		 
		 mylist = new ArrayList<HashMap<String, String>>();
	      
		 	AutoCompleteTextView textView = (AutoCompleteTextView)
	                findViewById(R.id.Nhap_mavung);
		 	
		 	ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
	                android.R.layout.simple_dropdown_item_1line, Provinces);
		 	textView.setAdapter(adapter1);
		 	textView.setThreshold(3);
		 			 			 	
		 	if(isOnline() == true)
			{
		 	Log.d(DEBUG_TAG, "internet connected: " + isOnline());
		 	
	        
		 	
	        xml = XMLfunctions.getXML(URL);
	        
	        doc = XMLfunctions.XMLfromString(xml);
	                
	        nodes = doc.getElementsByTagName("item");
	        
	        Log.d(TAG1, Long.toString(System.currentTimeMillis()));
			for (int i = 0; i < nodes.getLength(); i++) {
				
				map = new HashMap<String, String>();	
				Node itemNode = nodes.item(i);
				
				Element definitionElement = (Element) itemNode;
				
				NodeList wordDefinitionElements = (definitionElement).getElementsByTagName(ID);
				
				for(int j=0; j <wordDefinitionElements.getLength(); j++){
					
					Element wordDefinitionElement = (Element) wordDefinitionElements.item(j);
										
					map.put(id, XMLfunctions.getValue(wordDefinitionElement, ID));										
				}
				
				NodeList wordDefinitionElements2 = (definitionElement).getElementsByTagName(CODE);
				for(int j=0; j <wordDefinitionElements2.getLength(); j++){
					
					Element wordDefinitionElement = (Element) wordDefinitionElements2.item(j);
										
					map.put("code",XMLfunctions.getValue(wordDefinitionElement, CODE));
					
				}
				
				NodeList wordDefinitionElements3 = (definitionElement).getElementsByTagName(NAME);
				for(int j=0; j <wordDefinitionElements3.getLength(); j++){
					
					Element wordDefinitionElement = (Element) wordDefinitionElements3.item(j);
										
					map.put("name",XMLfunctions.getValue(wordDefinitionElement, NAME));
					
				}
				
				mylist.add(map);
        /*
         * 		Insert ID and Province Name to Database
         */            				
				
				
				//db.checkDataBase();
		        //db.insertProvince(map.get("id"),map.get("name"),map.get("name"));
				
				
				
		        
		        
			}		
			
			Log.d(TAG2, Long.toString(System.currentTimeMillis()));
			Mytask task = new Mytask();
			task.execute();
			Log.d(TAG3, Long.toString(System.currentTimeMillis()));
		
			}
		 	
		// if connection == false
		else {
				
				db.open(); 
				Cursor c = db.getAllProvince();
				if (c.moveToFirst())
		        {
		            do {          
		            	HashMap<String, String> map = new HashMap<String, String>();
		            		map.put(id, c.getString(0));
		            		map.put("name", c.getString(2));
		            		
		            		mylist.add(map);
		       //         DisplayContact(c);
		            } while (c.moveToNext());
		        }
				
				db.close();
			}
			
	        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.province_item, 
	                        new String[] { id,"name"}, 
	                        new int[] { R.id.item_id, R.id.item_name });
	        
	        setListAdapter(adapter);
	        
	        final ListView lv = getListView();
	        lv.setTextFilterEnabled(true);	
	        lv.setOnItemClickListener(new OnItemClickListener() {
	        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        		
	        		@SuppressWarnings("unchecked")
					HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	        		
	        		//Toast.makeText(MainActivity.this, "ID " + o.get("id")+" "+  o.get("ProvinceName")+ " was clicked.", Toast.LENGTH_LONG).show(); 
	        		Bundle sendbundle = new Bundle();
	        		sendbundle.putString("id", o.get(id));
	        		sendbundle.putString("ProvinceName", o.get("ProvinceName"));
	        		Intent i = new Intent(ProvinceProperties.this,LotteryResult.class);
	        		i.putExtras(sendbundle);
	        		startActivity(i);
				}
			});			
			
	 }
	 
	 public void DisplayContact(Cursor c)
	    {
	        Toast.makeText(this, 
	                "id: " + c.getString(0) + "\n" +
	                "Name: " + c.getString(1) + "\n",
	                Toast.LENGTH_LONG).show();        
	    } 	    
	 
	// Check a Device's Network Connection
	 public boolean isOnline() {
	 		    ConnectivityManager connMgr = (ConnectivityManager) 
	 		            getSystemService(Context.CONNECTIVITY_SERVICE);
	 		    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
	 		    return (networkInfo != null && networkInfo.isConnected());
	 		}	     
	 	 
	 private class Mytask extends AsyncTask<String, Void, String>{
		 
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			
		    db.open();
			for (int i = 0; i < mylist.size() ; i++){
				/*db.checkDataBase();
				db.insertProvince(map.get("id"),map.get("name"),map.get("name"));*/
				db.checkDataBase();
				db.insertProvince(mylist.get(i).get(id), mylist.get(i).get("name"), mylist.get(i).get("name"));
			}
			db.close();
			return null;
		}
		@Override
		protected void onPostExecute(String abc) {
			
		}
		
	 }
}
